﻿namespace anydata.Wrokers
{
    public class KernelHubWorker : BackgroundService
    {
        readonly List<KernelHub> _kernels;
        public KernelHubWorker(DataProvider coll,
            ILogger<KernelHubWorker> logger)
        {
            _kernels = new List<KernelHub>();
            foreach (var addr in Config.KernelAddr.Split(";"))
            {
                for (int i = 0; i < Config.KernelNum; i++)
                {
                    _kernels.Add(new KernelHub(coll, logger, addr));
                }
            }
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            for (var i = 0; i < _kernels.Count; i++)
            {
                await _kernels[i].StartAsync();
            }
            await base.StartAsync(cancellationToken);
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            for (var i = 0; i < _kernels.Count; i++)
            {
                await _kernels[i].StopAsync();
            }
            await base.StopAsync(cancellationToken);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                for (var i = 0; i < _kernels.Count; i++)
                {
                    await _kernels[i].PingAsync(stoppingToken);
                }
            }
        }
    }
}
